unit DataModule;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Db, IBDatabase, IBSQL, IBCustomDataset, IniFiles, Logger;

type
  TdmData = class(TDataModule)
    DB: TIBDatabase;
    procedure DataModuleCreate(Sender: TObject);
    procedure DataModuleDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    function CreateIBSQL(p_SQL: string): TIBSQL;
    function CreateIBDataset(p_SQL: string): TIBDataset;
  end;

var
  dmData: TdmData;
  Ini: TIniFile;
  Log: TLogger;

implementation

{$R *.DFM}

procedure TdmData.DataModuleCreate(Sender: TObject);
begin
  Log := TLogger.Create();
  Ini := TIniFile.Create( ChangeFileExt(ParamStr(0), '.INI') );
  Log.SetMinLevel( Ini.ReadString('Logging', 'Level', 'NOTICE') );
  DB.DatabaseName := Ini.ReadString( 'Database', 'Path', '' );
  DB.Open;
end;

procedure TdmData.DataModuleDestroy(Sender: TObject);
begin
  Ini.Free;
  Log.Free;
end;

function TdmData.CreateIBSQL(p_SQL: string): TIBSQL;
var tr: TIBTransaction;
begin
  result := TIBSQL.Create( self );
  result.Database := DB;

  tr := TIBTransaction.Create( result );
  Tr.DefaultDatabase := DB;
  Tr.Params.Add('read_committed');
  Tr.Params.Add('rec_version');
  Tr.Params.Add('nowait');

  result.Transaction := tr;
  result.SQL.Text := p_SQL;
  if p_SQL <> '' then begin
    tr.StartTransaction;
    if result.Params.Count = 0 then begin
      result.ExecQuery;
    end;
  end;
end;

function TdmData.CreateIBDataset(p_SQL: string): TIBDataset;
var tr: TIBTransaction;
begin
  result := TIBDataset.Create( self );
  result.Database := DB;

  tr := TIBTransaction.Create( result );
  Tr.DefaultDatabase := DB;
  Tr.Params.Add('read_committed');
  Tr.Params.Add('rec_version');
  Tr.Params.Add('nowait');

  result.Transaction := tr;
  result.SelectSQL.Text := p_SQL;
  if p_SQL <> '' then begin
    tr.StartTransaction;
  end;
end;

end.
